package core

import (
    "crypto/tls"
	"errors"
	"time"
	"encoding/xml"
	"wxsdk/wxpay/utils/pay"
	"wxsdk/wxpay/utils/mapstruct"
	"github.com/astaxie/beego"
)

type WxCoPayClient struct {
	AppSecret      string
	TlsConfig      *tls.Config
	Timeout        time.Duration
}

func (c *WxCoPayClient) Excute(serverUrl string, request interface{}, response interface{}, checkSign bool) error{
	params := mapstruct.Struct2Map(request, "xml")
	params["nonce_str"] = payutils.GetNonceStr(32) //随机字符串
	params["sign"] = payutils.MakeSign(params, c.AppSecret)
	xmlString := payutils.Map2Xml(params)
	body, err := payutils.SendXmlRequest("POST", serverUrl, xmlString, c.TlsConfig, c.Timeout)
	if err != nil {
		return err
	}
	beego.Debug("body:", string(body))
	err = xml.Unmarshal(body, &response)
	if err != nil {
		return err
	}
	rspMap :=  mapstruct.Struct2Map(response, "xml")
	if rspMap["return_code"] != "SUCCESS" {
	    returnMsg := rspMap["return_msg"].(string)
		return errors.New(returnMsg)
	}
	if rspMap["result_code"] != "SUCCESS" {
	    errCodeDes := rspMap["err_code_des"].(string)
		return errors.New(errCodeDes)
	}
	// 校验回执签名
	if checkSign {
	    sign := payutils.MakeSign(rspMap, c.AppSecret)
		if rspMap["sign"] != sign {
			err = errors.New("response sign err")
			return err
		}
	}
	return nil
}

func GetWxCoPayClient(appSecret string,tlsConfig *tls.Config) *WxCoPayClient {
	return &WxCoPayClient{
		AppSecret: appSecret,
		TlsConfig: tlsConfig,     // 安全证书
		Timeout: 6,
	}
}
